
Math.easeInOutQuad = function (t, b, c, d) {
  t /= d / 2
  if (t < 1) {
    return c / 2 * t * t + b
  }
  t--
  return -c / 2 * (t * (t - 2) - 1) + b
}

// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
// var requestAnimFrame = (function () {
//   return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60) }
// })()
var requestAnimFrame = (function () {
  return function (callback, $this) {
    if ($this && $this.timeclear) {
      clearTimeout($this.timeclear)
    }
    if (!($this && $this.clearAutoScroll)) {
      $this.timeclear = window.setTimeout(callback, 1000 / 500)
    } else {

    }

  }
})()
/**
 * Because it's so fucking difficult to detect the scrolling element, just move them all
 * @param {number} amount
 */
function move(amount, _this, $this) {
  if (!($this && $this.clearAutoScroll)) {
    if (_this) {
      _this.scrollTop = amount
    } else {
      document.documentElement.scrollTop = amount
      document.body.parentNode.scrollTop = amount
      document.body.scrollTop = amount
    }
  }

}

function position(_this) {
  if (_this) {
    return _this.scrollTop
  } else {
    return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
  }

}

/**
 * @param {number} to
 * @param {number} duration
 * @param {Function} callback
 */
export function scrollTo(to, duration, callback, _this, $this) {
  const start = position(_this)
  const change = to - start
  const increment = 20
  let currentTime = 0
  duration = (typeof (duration) === 'undefined') ? 500 : duration
  var animateScroll = function () {

    // increment the time
    if (!($this && $this.clearAutoScroll)) {
      currentTime += increment
    } else {
      currentTime = duration
    }
    // find the value with the quadratic in-out easing function
    var val = Math.easeInOutQuad(currentTime, start, change, duration)
    // move the document.body
    if (!($this && $this.clearAutoScroll)) {
      // console.log($this.clearAutoScroll,"ZZZZZZZZZZZZZZZZZZZZZZZZZZZ")
      move(val, _this, $this)
    } else {
      // console.log($this.clearAutoScroll,"********************************************")
      return
    }
    // do the animation unless its over
    if (currentTime < duration) {
      requestAnimFrame(animateScroll, $this)
    } else {

      if (callback && typeof (callback) === 'function') {
        // the animation is done so lets callback
        callback()
      }
    }
  }
  animateScroll()
}
